package stark.app.function.ve;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;

import androidx.annotation.Nullable;

import com.stark.picselect.PhotoSelectorBuilder;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.interfaces.OnSelectResultListener;
import com.stark.ve.VideoEditorEntry;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import VideoHandle.EpAudio;
import VideoHandle.EpEditor;
import VideoHandle.EpVideo;
import VideoHandle.OnEditorListener;
import stark.app.R;
import stark.app.databinding.ActivityVideoEditorDemoBinding;
import stark.common.basic.base.BaseNoModelActivity;
import stark.common.basic.constant.Extra;
import stark.common.basic.media.IMediaSelector;
import stark.common.basic.media.MediaInfo;
import stark.common.basic.utils.LogUtil;

/**
 * Author：daizhongbin on 2021/3/19
 * Email：1027154338@qq.com
 * Desc: 视频编辑videoeditor模块使用示例界面
 */
public class VideoEditorDemoActivity extends BaseNoModelActivity<ActivityVideoEditorDemoBinding> {

    private enum Operation {
        VIDEO_SPEED,    //视频变速
        VIDEO_SEGMENT_SPEED,    //视频分段变速
        VIDEO_SPEED_RET,    //视频变速 For Ret
        VIDEO_CUT,      //视频剪切
        VIDEO_REVERSE,  //视频倒放
        VIDEO_CROP,     //视频裁剪
        VIDEO_ROTATE,   //视频旋转
        VIDEO_FILTER,   //视频滤镜
        EXTRACT_AUDIO,  //提取音频
        EXTRACT_AUDIO_RET,  //提取音频 For Ret
        VIDEO_GIF,      //视频转GIF
        VIDEO_GIF_RET,  //视频转GIF For Ret
        VIDEO_MERGE,    //视频拼接
        VIDEO_COMPRESS, //视频压缩
        VIDEO_FMT_CONVERT, //视频格式转换
    }

    private static final int REQ_GIF_RET = 1;
    private static final int REQ_AUDIO_RET = 2;
    private static final int REQ_SPEED_RET = 3;

    @Override
    protected int onCreate() {
        return R.layout.activity_video_editor_demo;
    }

    @Override
    protected void initView() {
        mDataBinding.btnVideoSpeed.setOnClickListener(view -> {
            goEdit(Operation.VIDEO_SPEED);
        });
        mDataBinding.btnSegmentSpeed.setOnClickListener(v -> {
            goEdit(Operation.VIDEO_SEGMENT_SPEED);
        });
        mDataBinding.btnVideoSpeedRet.setOnClickListener(view -> {
            goEdit(Operation.VIDEO_SPEED_RET);
        });
        mDataBinding.btnVideoCut.setOnClickListener(view -> {
            goEdit(Operation.VIDEO_CUT);
        });
        mDataBinding.btnVideoReverse.setOnClickListener(view -> {
            goEdit(Operation.VIDEO_REVERSE);
        });
        mDataBinding.btnVideoCrop.setOnClickListener(view -> {
            goEdit(Operation.VIDEO_CROP);
        });
        mDataBinding.btnVideoRotate.setOnClickListener(view -> {
            goEdit(Operation.VIDEO_ROTATE);
        });
        mDataBinding.btnVideoFilter.setOnClickListener(view -> {
            goEdit(Operation.VIDEO_FILTER);
        });
        mDataBinding.btnExtractAudio.setOnClickListener(view -> {
            goEdit(Operation.EXTRACT_AUDIO);
        });
        mDataBinding.btnExtractAudioRet.setOnClickListener(view -> {
            goEdit(Operation.EXTRACT_AUDIO_RET);
        });
        mDataBinding.btnVideoGif.setOnClickListener(view -> {
            goEdit(Operation.VIDEO_GIF);
        });
        mDataBinding.btnVideoGifRet.setOnClickListener(view -> {
            goEdit(Operation.VIDEO_GIF_RET);
        });
        mDataBinding.btnVideoMerge.setOnClickListener(view -> {
            goEdit(Operation.VIDEO_MERGE);
        });
        mDataBinding.btnVideoCompress.setOnClickListener(v -> {
            goEdit(Operation.VIDEO_COMPRESS);
        });
        mDataBinding.btnVideoFmtConvert.setOnClickListener(v -> {
            goEdit(Operation.VIDEO_FMT_CONVERT);
        });
        mDataBinding.btnVideoInsertBg.setOnClickListener(view -> {
            EpAudio audio = new EpAudio("/storage/emulated/0/input.mp3");
            audio.setTempo(2);
            audio.setPitch(0.5);
//            audio.clip(0,5);
            EpAudio[] audios = new EpAudio[]{audio, new EpAudio("/storage/emulated/0/input.mp3")};
            EpEditor.audioExec(audio, "/storage/emulated/0/" + String.format("%d.mp3", System.currentTimeMillis()), new OnEditorListener()
//            EpEditor.audioMix(Arrays.asList(audios),"/storage/emulated/0/"+String.format("%d.mp3",System.currentTimeMillis()), new OnEditorListener()
//                    EpEditor.audioConcat(Arrays.asList(audios),"/storage/emulated/0/"+String.format("%d.mp3",System.currentTimeMillis()), new OnEditorListener()
//            EpEditor.insertBgColor("/storage/emulated/0/test.mp4", 360,360,"0xFF0000","/storage/emulated/0/"+String.format("%d.mp4",System.currentTimeMillis()), new OnEditorListener()
//                    EpEditor.insertBgWithSize("/storage/emulated/0/test.jpg", "/storage/emulated/0/test.mp4", 360,360,"/storage/emulated/0/"+String.format("%d.mp4",System.currentTimeMillis()), new OnEditorListener()
//                    EpEditor.insertBgWithAlpha("/storage/emulated/0/test.jpg", "/storage/emulated/0/test.mp4", 0.5,"/storage/emulated/0/"+String.format("%d.mp4",System.currentTimeMillis()), new OnEditorListener()
            {
                @Override
                public void onSuccess() {
                    LogUtil.e("onSuccess");
                }

                @Override
                public void onFailure() {
                    LogUtil.e("onFailure");
                }

                @Override
                public void onProgress(float progress) {
                    LogUtil.e("onProgress: ", progress);

                }
            });
        });
        mDataBinding.btnVideoAddText.setOnClickListener(view -> {
            EpVideo[] videos = new EpVideo[]{new EpVideo("/storage/emulated/0/input.mp4"), new EpVideo("/storage/emulated/0/test.mp4")};

            EpEditor.merge(Arrays.asList(videos), new EpEditor.OutputOption("/storage/emulated/0/" + String.format("%d.mp4", System.currentTimeMillis())), new OnEditorListener() {
                //            EpVideo ev = new EpVideo("/storage/emulated/0/test.mp4");
//            ev.addText(new EpText(0,0,30, EpText.Color.Red,"/storage/emulated/0/test.ttf","Hello,FFMPEG",null));
//            EpEditor.exec(ev,new EpEditor.OutputOption("/storage/emulated/0/"+String.format("%d.mp4",System.currentTimeMillis())), new OnEditorListener() {
//            EpEditor.addText("/storage/emulated/0/test.mp4", "/storage/emulated/0/" + String.format("%d.mp4", System.currentTimeMillis()), new OnEditorListener() {
                @Override
                public void onSuccess() {
                    LogUtil.e("onSuccess");
                }

                @Override
                public void onFailure() {
                    LogUtil.e("onFailure");
                }

                @Override
                public void onProgress(float progress) {
                    LogUtil.e("onProgress: ", progress);

                }
            });
        });
    }

    @Override
    protected void initData() {
        /**
         * 如果用到了模块内部需要选择媒体素材的功能，则必须调用该接口初始化媒体选择器
         */
        VideoEditorEntry.initMediaSelector(new IMediaSelector() {
            @Override
            public void onSelectMedia(Activity activity, Type type, int minCount, int maxCount, boolean copyPrivate, IRetCallback callback) {
                /**
                 * 这里如果想用其它的媒体素材选择模块，修改这里的代码即可，这样就不用改
                 * videoeditor模块内部的代码，videoeditor模块也就不需要依赖任何的媒体选择模块
                 */
                PhotoSelectorBuilder.builder(activity)
                        .mode(getMode(type))
                        .minCount(minCount)
                        .maxCount(maxCount)
                        .isCopyToPrivate(copyPrivate)
                        .listener(new OnSelectResultListener<List<SelectMediaEntity>>() {
                            @Override
                            public void onResult(List<SelectMediaEntity> data) {
                                if (callback != null) {
                                    callback.onResult(convert2MediaInfo(data));
                                }
                            }
                        });
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQ_GIF_RET) {
                Uri uri = data.getParcelableExtra(Extra.RET_URI);
                mDataBinding.tvRet.setText("保存的Gif的Uri为：" + uri.toString());
            } else if (requestCode == REQ_AUDIO_RET) {
                Uri uri = data.getParcelableExtra(Extra.RET_URI);
                mDataBinding.tvRet.setText("保存的音频的Uri为：" + uri.toString());
            } else if (requestCode == REQ_SPEED_RET) {
                Uri uri = data.getParcelableExtra(Extra.RET_URI);
                mDataBinding.tvRet.setText("保存的视频变速的Uri为：" + uri.toString());
            }
        }
    }

    private PhotoConfig.Mode getMode(IMediaSelector.Type type) {
        PhotoConfig.Mode mode = PhotoConfig.Mode.ALL;
        switch (type) {
            case VIDEO:
                mode = PhotoConfig.Mode.VIDEO;
                break;
            case IMAGE:
                mode = PhotoConfig.Mode.PHOTO;
                break;
        }
        return mode;
    }

    private List<MediaInfo> convert2MediaInfo(List<SelectMediaEntity> data) {
        if (data == null || data.size() == 0) {
            return null;
        }
        List<MediaInfo> mediaInfoList = new ArrayList<>();
        MediaInfo mediaInfo = null;
        for (SelectMediaEntity entity : data) {
            mediaInfo = new MediaInfo();
            mediaInfo.setPath(entity.getTargetPath());
            mediaInfoList.add(mediaInfo);
        }
        return mediaInfoList;
    }

    private void goEdit(Operation operation) {
        PhotoSelectorBuilder.builder(this)
                .mode(PhotoConfig.Mode.VIDEO)
                .maxCount(1)
                .listener(new OnSelectResultListener<List<SelectMediaEntity>>() {
                    @Override
                    public void onResult(List<SelectMediaEntity> data) {
                        String path = data.get(0).getTargetPath();
                        switch (operation) {
                            case VIDEO_SPEED:
                                VideoEditorEntry.enterSpeed(VideoEditorDemoActivity.this, path);
                                break;
                            case VIDEO_SEGMENT_SPEED:
                                VideoSegmentChangeSpeedActivity.start(VideoEditorDemoActivity.this, path);
                                break;
                            case VIDEO_SPEED_RET:
                                VideoEditorEntry.enterSpeedForRet(VideoEditorDemoActivity.this, path, REQ_SPEED_RET);
                                break;
                            case VIDEO_CUT:
                                VideoEditorEntry.enterCut(VideoEditorDemoActivity.this, path);
                                break;
                            case VIDEO_REVERSE:
                                VideoEditorEntry.enterReverse(VideoEditorDemoActivity.this, path);
                                break;
                            case VIDEO_CROP:
                                VideoEditorEntry.enterCrop(VideoEditorDemoActivity.this, path);
                                break;
                            case VIDEO_ROTATE:
                                VideoEditorEntry.enterRotate(VideoEditorDemoActivity.this, path);
                                break;
                            case VIDEO_FILTER:
                                VideoEditorEntry.enterFilter(VideoEditorDemoActivity.this, path);
                                break;
                            case EXTRACT_AUDIO:
                                VideoEditorEntry.enterExtractAudio(VideoEditorDemoActivity.this, path);
                                break;
                            case EXTRACT_AUDIO_RET:
                                VideoEditorEntry.enterExtractAudioForRet(VideoEditorDemoActivity.this, path, REQ_AUDIO_RET);
                                break;
                            case VIDEO_GIF:
                                VideoEditorEntry.enterVideoGif(VideoEditorDemoActivity.this, path);
                                break;
                            case VIDEO_GIF_RET:
                                VideoEditorEntry.enterVideoGifForRet(VideoEditorDemoActivity.this, path, REQ_GIF_RET);
                                break;
                            case VIDEO_MERGE:
                                VideoEditorEntry.enterMerge(VideoEditorDemoActivity.this, path);
                                break;
                            case VIDEO_COMPRESS:
                                VideoEditorEntry.enterCompress(VideoEditorDemoActivity.this, path);
                                break;
                            case VIDEO_FMT_CONVERT:
                                VideoEditorEntry.enterFmtConvert(VideoEditorDemoActivity.this, path);
                                break;
                        }
                    }
                });
    }
}
